<?php

namespace Cmf\Plugins;

use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Dispatcher;
use Phalcon\Mvc\Dispatcher\Exception as DispatcherException;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;

/**
 * NotFoundPlugin
 *
 * Handles not-found controller/actions
 */
class NotFoundPlugin extends Plugin
{

    /**
     * This action is executed before execute any action in the application
     *
     * @param Event      $event
     * @param Dispatcher $dispatcher
     */
    public function beforeException(Event $event, MvcDispatcher $dispatcher, DispatcherException $exception)
    {
        if ($exception instanceof DispatcherException) {
            switch ($exception->getCode()) {
                case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                    $logger = $this->getDI()->getShared('log');
                    $logger->error('浏览器重定向');
                    $this->response->redirect('errors/show404');

                    return false;
                    break;
                case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                    $logger = $this->getDI()->getShared('log');
                    $logger->error('该动作不存在');
                    $this->response->redirect('errors/show404');

                    return false;
                    break;

            }
        }

        $this->response->redirect('errors/show500');

        return false;
    }
}
